package com.sunflower.common.mybatis.converter;

import com.baomidou.mybatisplus.annotation.IEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * @Classname StringToEnumConverterFactory
 * @Description TODO
 * @Date 2021/6/25 9:40
 * @Created by SunLuQuan
 * <p>
 * 所有继承ienum类的枚举的转换器
 * 根据 aClass 和 ienum -- value 确定转换为对象的枚举类
 */
@Component
public class IntegerToEnumConverterFactory implements ConverterFactory<Integer, IEnum> {

    @Override
    public <T extends IEnum> Converter<Integer, T> getConverter(Class<T> targetType) {
        return new IntegerToEnum(targetType);
    }

    private static class IntegerToEnum<T extends IEnum> implements Converter<Integer, T> {
        private final Class<T> clzz;

        private final T[] iEnums;

        public IntegerToEnum(Class<T> clzz) {
            this.clzz = clzz;
            this.iEnums = clzz.getEnumConstants();
        }

        @Override
        public T convert(Integer source) {
            for (T iEnum : iEnums) {
                if (iEnum.getValue() == source) return iEnum;
            }
            throw new IllegalArgumentException();
        }
    }
}
